//========================文件上传=================
const uploader = new ChunkUploader({
    uploadUrl: baseUrl+'upload/chunk',
    mergeUrl: baseUrl+'upload/merge',
    chunkSize: 0.5 * 1024 * 1024, // 1MB
    onProgress: (fileName, chunkIndex, totalChunks) => {
        console.log(`Uploading ${fileName} totalChunks ${totalChunks} chunk ${chunkIndex}`);
    },
    onComplete: (fileName,type) => {
        showFiles(fileName,type);
        console.log(`Completed uploading ${fileName}`);
    },
});
//房间列表添加
function addRoom(room) {
    // 模拟添加新房间到列表
    const roomsList = document.getElementById('rooms');
    const newRoomItem = document.createElement('div');
    newRoomItem.className = 'list-item';
    newRoomItem.id = `${room.roomId}`;
    newRoomItem.innerHTML = `
                <div class="avatar">
                    <i class="fas fa-hashtag"></i>
                </div>
                <div class="info">
                    <h4>${room.roomName}</h4>
                    <p>${room.userCount}人在线</p>
                </div>
            `;
    // 插入到新建房间按钮之前
    roomsList.insertBefore(newRoomItem, newRoomBtn);
    //增加点击事件
    document.querySelectorAll('#rooms .list-item:not(#new-room-btn)').forEach(item => {
        item.addEventListener('click', async () => {
            document.querySelectorAll('#rooms .list-item').forEach(i => i.classList.remove('active'));
            let data = {
                roomId: item.id,
                userName: userName,
                userId: userId
            }
            // 离开房间
            await leaveRoom(data);
            // 加入房间
            await joinRoom(data);
            item.classList.add('active');
            // 这里可以添加切换房间的逻辑
            const roomName = item.querySelector('h4').textContent;
            document.querySelector('.room-info h3').textContent = roomName;
        });
    });
}
//房间列表查询
async function queryRoomFun() {
    const rooms = document.getElementById('rooms');
    rooms.querySelectorAll('#rooms .list-item:not(#new-room-btn)').forEach(item => item.remove());
    const roomList = await queryRoom();
    let data = roomList.data;
    // 添加公共房间到数组前面
    data.forEach(item => {
        addRoom(item);
    });
    //增加选中状态
    if(roomId){
        document.getElementById(roomId).classList.add('active');
    }
}

//用户列表添加
function addUser(user) {
    const usersList = document.getElementById('users');
    const newUserItem = document.createElement('div');
    newUserItem.className = 'list-item';
    newUserItem.id = `${user.userId}`;
    newUserItem.innerHTML = `
                            <div class="info">
                                <h4>${user.userName}</h4>
                                <p>在线</p>
                            </div>
                            <div class="status online"></div>
                        `;
    // 插入到新建房间按钮之前
    usersList.appendChild(newUserItem);
}

// 处理选择的文件
function handleFiles(files, type) {
    if (!files || files.length === 0) return;
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        // 检查文件类型
        if ((type === 'image' && !file.type.startsWith('image/'))) {
            alert('请选择有效的图片文件');
            continue;
        }

        if ((type === 'video' && !file.type.startsWith('video/'))) {
            alert('请选择有效的视频文件');
            continue;
        }
        uploader.uploadFile(file, type);
    }

}

// 上传成功之后回调
function showFiles(filePath, type) {
    // 添加到媒体文件数组
    mediaFiles.push({
        type,
        url: filePath
    });
    updatePreview();
}

// 更新预览区域
function updatePreview() {
    if (mediaFiles.length === 0) {
        previewContainer.classList.remove('active');
        previewContainer.innerHTML = '';
        return;
    }

    previewContainer.classList.add('active');
    previewContainer.innerHTML = '';

    mediaFiles.forEach((media, index) => {
        const previewItem = document.createElement('div');
        previewItem.className = 'preview-item';

        if (media.type === 'image') {
            previewItem.innerHTML = `
                        <img src="${media.url}" alt="预览图片">
                        <button class="remove-btn" data-index="${index}">&times;</button>
                    `;
        } else {
            previewItem.innerHTML = `
                        <video src="${media.url}" controls></video>
                        <button class="remove-btn" data-index="${index}">&times;</button>
                    `;
        }

        previewContainer.appendChild(previewItem);
    });

    // 添加删除按钮事件
    document.querySelectorAll('.remove-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const index = parseInt(e.target.getAttribute('data-index'));
            mediaFiles.splice(index, 1);
            updatePreview();
            e.stopPropagation();
        });
    });
}

// 发送消息
function sendMessage() {
    const input = document.querySelector('.chat-input .input-group .send-input input');
    const message = input.value.trim();
    if (message) {

        //推送消息到房间
        let data = {
            from: userId,
            toFrom: toUserId,
            fromName: userName,
            content: {
                msg: message,
                file: mediaFiles
            },
            type: 'msg'
        }
        wxUtil.sendMessage(userId, data);


        const messagesContainer = document.querySelector('.chat-messages');
        const now = new Date();
        const timeString = now.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});

        const newMessage = document.createElement('div');
        newMessage.className = 'message self';
        newMessage.innerHTML = `
                    <div class="content">
                        <div class="info">
                            <h4>我</h4>
                            <time>${timeString}</time>
                        </div>
                        <div class="text">
                            ${message}
                        </div>
                    </div>
                `;
        messagesContainer.appendChild(newMessage);
        input.value = '';
        if (mediaFiles.length > 0) {
            // 添加媒体内容
            mediaFiles.forEach(media => {
                if (media.type === 'image') {
                    newMessage.querySelector('.content').innerHTML += `
                            <div class="media">
                                <img src="${media.url}" alt="图片">
                            </div>
                        `;
                } else {
                    //截图视频文件后缀
                    const lastDot = media.url.lastIndexOf('.');
                    const types = media.url.slice(lastDot + 1);
                    newMessage.querySelector('.content').innerHTML += `
                            <div class="media">
                                <video controls>
                                    <source src="${media.url}" type="${media.type}/${types}">
                                    您的浏览器不支持视频播放
                                </video>
                            </div>
                        `;
                }
            });
            mediaFiles = [];
            updatePreview();
        }
        // 滚动到底部
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
}

